-- ============================================
-- CRASH / FUSEE - ComputerCraft / CC:Tweaked
-- Nécessite : Advanced Computer + Advanced Monitor (couleur)
-- ============================================

local MISE = 1
local points = 100

local TICK = 0.1        -- intervalle d'animation (secondes)
local GROWTH = 0.02      -- croissance du multiplicateur par tick (2%)
local MAX_TIME = 20      -- duree max affichable sur le graphe (secondes)
local MAX_MULT_SCALE = 50 -- echelle logarithmique du graphe

local mon = peripheral.find("monitor")
if not mon then
    error("Aucun monitor trouve ! Colle un Advanced Monitor a cote du computer.")
end

mon.setTextScale(0.5)
local prevTerm = term.redirect(mon)
local w, h = term.getSize()

local graphTop, graphBottom = 6, h - 3
local graphLeft, graphRight = 1, w

local function centerText(y, text, textColor, bgColor)
    term.setBackgroundColor(bgColor or colors.black)
    term.setTextColor(textColor or colors.white)
    local x = math.floor((w - #text) / 2) + 1
    term.setCursorPos(x, y)
    term.write(text)
end

local function fillArea(x1, y1, x2, y2, bg)
    term.setBackgroundColor(bg)
    for y = y1, y2 do
        term.setCursorPos(x1, y)
        term.write(string.rep(" ", x2 - x1 + 1))
    end
end

-- === GENERATION DU POINT DE CRASH ===
-- Distribution type "crash game" avec une petite marge maison (~4%)
local function generateCrashPoint()
    local r = math.random()
    if r < 0.01 then r = 0.01 end
    if r > 0.999 then r = 0.999 end
    local crash = (1 / (1 - r)) * 0.96
    if crash < 1.0 then crash = 1.0 end
    if crash > MAX_MULT_SCALE then crash = MAX_MULT_SCALE end
    return crash
end

-- === GRAPHE ===
local function plotPoint(elapsed, multiplier, col)
    local x = graphLeft + math.floor((elapsed / MAX_TIME) * (graphRight - graphLeft))
    x = math.min(graphRight, math.max(graphLeft, x))

    local ratio = math.log(multiplier) / math.log(MAX_MULT_SCALE)
    local y = graphBottom - math.floor(ratio * (graphBottom - graphTop))
    y = math.min(graphBottom, math.max(graphTop, y))

    term.setBackgroundColor(col)
    term.setCursorPos(x, y)
    term.write(" ")
end

local function drawHeader(multiplier, status, statusColor)
    fillArea(1, 1, w, graphTop - 1, colors.black)
    centerText(1, "=== CASINO COMPUTERCRAFT ===", colors.yellow)
    centerText(2, "CRASH / FUSEE", colors.white)
    centerText(3, "Points : " .. points, colors.lime)
    local multColor = colors.lime
    if status then multColor = statusColor end
    centerText(4, string.format("x%.2f", multiplier), multColor)
end

-- === BOUTON ENCAISSER ===
local cashButton = {}
local function drawCashButton()
    local label = "ENCAISSER"
    local bw = #label + 4
    local x1 = math.floor((w - bw) / 2) + 1
    local y = h - 1
    term.setBackgroundColor(colors.orange)
    term.setTextColor(colors.white)
    for x = x1, x1 + bw - 1 do
        term.setCursorPos(x, y)
        term.write(" ")
    end
    term.setCursorPos(x1 + 2, y)
    term.write(label)
    cashButton = { x1 = x1, x2 = x1 + bw - 1, y = y }
end

-- === UNE MANCHE ===
local function playRound()
    if points < MISE then
        drawHeader(1.0, "PLUS ASSEZ DE POINTS !", colors.red)
        sleep(2)
        return
    end
    points = points - MISE

    fillArea(graphLeft, graphTop, graphRight, graphBottom, colors.black)

    local crashPoint = generateCrashPoint()
    local multiplier = 1.0
    local elapsed = 0
    local cashedOut = false

    drawHeader(multiplier)
    drawCashButton()
    plotPoint(elapsed, multiplier, colors.lime)

    local timerId = os.startTimer(TICK)

    while true do
        local event, p1, p2, p3 = os.pullEvent()

        if event == "timer" and p1 == timerId then
            elapsed = elapsed + TICK
            multiplier = multiplier * (1 + GROWTH)

            if multiplier >= crashPoint then
                plotPoint(elapsed, crashPoint, colors.red)
                drawHeader(crashPoint, "CRASH", colors.red)
                fillArea(cashButton.x1, cashButton.y, cashButton.x2, cashButton.y, colors.black)
                break
            end

            plotPoint(elapsed, multiplier, colors.lime)
            drawHeader(multiplier)
            timerId = os.startTimer(TICK)

        elseif event == "monitor_touch" then
            local tx, ty = p2, p3
            if tx >= cashButton.x1 and tx <= cashButton.x2 and ty == cashButton.y then
                cashedOut = true
                break
            end
        end
    end

    local msg, msgColor, gain

    if cashedOut then
        gain = math.floor(MISE * multiplier)
        points = points + gain
        msg = "ENCAISSE a x" .. string.format("%.2f", multiplier) .. " ! +" .. gain
        msgColor = colors.lime
    else
        gain = 0
        msg = "CRASH a x" .. string.format("%.2f", crashPoint) .. " ! Perdu."
        msgColor = colors.red
    end

    centerText(h - 1, msg, msgColor)
    sleep(2.5)
end

-- === ECRAN D'ACCUEIL ===
local button = {}

local function drawIdle()
    term.setBackgroundColor(colors.black)
    term.clear()
    centerText(1, "=== CASINO COMPUTERCRAFT ===", colors.yellow)
    centerText(2, "CRASH / FUSEE", colors.white)
    centerText(3, "Points : " .. points, colors.lime)
    centerText(5, "Le multiplicateur grimpe... encaisse avant le crash !", colors.lightGray)

    local label = "MISER (" .. MISE .. " point) ET LANCER"
    local bw = #label + 4
    local x1 = math.floor((w - bw) / 2) + 1
    local y = math.floor(h / 2)
    term.setBackgroundColor(colors.green)
    term.setTextColor(colors.white)
    for x = x1, x1 + bw - 1 do
        term.setCursorPos(x, y)
        term.write(" ")
    end
    term.setCursorPos(x1 + 2, y)
    term.write(label)
    button = { x1 = x1, x2 = x1 + bw - 1, y = y }
end

-- === PROGRAMME PRINCIPAL ===
drawIdle()

while true do
    local event, side, x, y = os.pullEvent("monitor_touch")
    if x >= button.x1 and x <= button.x2 and y == button.y then
        playRound()
        drawIdle()
    end
end